package linkfinders;

import http.HTTPLoader;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author eric
 *
 */
public class HTTPLinks implements ILinkFinder
{
	private ArrayList<Link> visited=new ArrayList<Link>();
	
	
	
	/* (non-Javadoc)
	 * @see linkfinders.ILinkFinder#getLinksFromUrl(java.lang.String)
	 */
	@Override
	public ArrayList<? extends Link> getLinksFromUrl(String url)
	{
		String html=HTTPLoader.getTextFile(url);
		return getLinksFromString(html,url);
	}
	

	/* (non-Javadoc)
	 * @see linkfinders.ILinkFinder#getLinksFromString(java.lang.String)
	 */
	@Override
	public ArrayList<? extends Link> getLinksFromString(String s, String url)
	{
		ArrayList<Link> links=new ArrayList<Link>();
		String folder=getFolder(url);
		String regexp="(<a href=\".*\">.*</a>)";
		String regexp2="href=\".*\"";
		Pattern p = Pattern.compile(regexp);
		Pattern p2= Pattern.compile(regexp2);
		Matcher m = p.matcher(s);
		Matcher m2;
		
		while(m.find())
		{
			m2=p2.matcher(m.group());
			while(m2.find())
			{
				String temp=m2.group();
				temp=temp.substring(6);
				temp=temp.substring(0, temp.indexOf('"'));
				if(!temp.startsWith("http"))
				{
					if(temp.startsWith("/"))
						temp=temp.substring(1);
					temp=folder+temp;
				}
				links.add(new Link(temp));
			}
		}
		return links;
	}


	/* (non-Javadoc)
	 * @see linkfinders.ILinkFinder#getLinksDepthFromString(java.lang.String, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<? extends Link> getLinksDepthFromString(String s, String url, int depth)
	{
		ArrayList<Link> links=(ArrayList<Link>) getLinksFromString(s,url);
		ArrayList<Link> ltemp=new ArrayList<Link>();
		if(depth>0)
		{
			depth--;
			for(Link stemp : links)
			{
				if (!visited.contains(stemp))
				{
					String html = HTTPLoader.getTextFile(stemp.getUrl());
					visited.add(stemp);
					ltemp.addAll(getLinksDepthFromString(html, url, depth));
				}
			}
		}
		for(Link t : ltemp)
		{
			if(!links.contains(t))
				links.add(t);
		}
		if(depth==0)
			visited.clear();
		return links;
	}
	

	@Override
	public ArrayList<? extends Link> getLinksDepthFromUrl(String url, int depth)
	{
		String html=HTTPLoader.getTextFile(url);
		return getLinksDepthFromString(html, url,depth);
	}


	@Override
	public String getFolder(String url)
	{
		if(!url.startsWith("http://") && !url.startsWith("ftp://"))
			url="http://"+url;
		if(url.endsWith("/"))
			return url;
		url=url.substring(0, url.lastIndexOf('/'));
		return url+"/";
	}
}
